<template>
<div class="attrGroupSearchWrapper ui segment" v-if="show">
  <!-- <p>
    <button class="ui circular icon button tiny" @click.stop.prevent="addGroup()">添加分组<i class="icon plus"></i>
      </button>
  </p> -->
  <draggable element="div" v-if="attr.length>0" v-model="attr" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false" @change="hlChange">
    <transition-group type="transition" :name="'flip-list'" tag="div">

      <div v-for="(val,index) in attr" class="ui compact message" :key="index">
        <sort_item :info="val" model="Attr"></sort_item>
      </div>
    </transition-group>
  </draggable>

  <div v-if="group.length>0" v-for="(g,gind) in group" class="ui vertical stackable menu">
    <div class="header item">
      {{group[gind].title}}</div>
    <draggable element="div" v-model="attr_group[gind]" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false" @change="onChange">
      <transition-group type="transition" :name="'flip-list'" tag="div">
        <sort_item :info="val" model="Attr" v-for="(val,index) in attr_group[gind]" class="item" :key="index">
          <i class="icon remove" @click.stop.prevent="removeItem(gind,index)"></i>
        </sort_item>
      </transition-group>
    </draggable>
  </div>
</div>
</template>

<script type="text/ecmascript-6">
import tool from 'src/util/tool';
import util from '_util/index';
import draggable from 'vuedraggable';
import RP from 'src/util/common/attr_sort';

import sort_item from 'components/common/sort_item'

const IMGPRE = tool.IMGPRE

export default {
  data() {
    return {
      // vals: []
      plist: [],
      attr: [],
      // attr2: [],
      attr_group: [],
      group: [],
      group_str: '',
      attr_group_str: '',
      editable: true,
      isDragging: false,
      delayedDragging: false
    }
  },
  components: {
    draggable,sort_item
  },
  methods: {
    onChange(info) {
      // tool.cl(info)
      if(!info.added)
        return;
      let el = info.added.element
      let _id = el ? el.id : null
      if (_id) {
        let eventVue = util.store.get(this,'eventVue');
        eventVue.$emit('zipChange', _id)
      }
    },
    removeItem(gind, index) {
      let removed = this.attr_group[gind].splice(index, 1)[0]
      if (removed.id != -1) {
        this.attr.push(removed)

        let eventVue = util.store.get(this,'eventVue');
        eventVue.$emit('zipRemoved', removed)
      }
      if (this.attr_group[gind].length == 0) {
        this.init2()
        // this.group.splice(gind, 1)
        // this.attr_group.splice(gind, 1)
      }
    },
    toRemove(index) {
      this.group.splice(index, 1);
      let removed = this.attr_group.splice(index, 1)
      if (removed[0].length > 0) {
        removed[0].forEach(item => {
          if (item.id != -1)
            this.attr.push(item)
        });
      }
    },
    init2() {
      util.mywait(this, 'show', () => {
        RP.init2(this);
      });
    },
    pro_attr_group_str() {
      let hled = this.attr_group.map(group => {
        return group.map(field => {
          return field.id
        })
      })
      this.attr_group_str = JSON.stringify(hled)
      this.setEditvo('attr_group_str_zip')
    },
    pro_group_str() {
      this.group_str = JSON.stringify(this.group)
      this.setEditvo('group_str_zip')
    },
    setEditvo(key) {
      let vo = this.$store.state.global.editVo
      vo[key] = this[key.replace('_zip', '')];
      util.store.commit(this,'setEditVo', vo)
    },
    hlChange() {},
    onMove({
      relatedContext,
      draggedContext
    }) {
      const relatedElement = relatedContext.element;
      const draggedElement = draggedContext.element;
      // tool.cl(relatedElement, draggedElement)
      let rl = relatedContext.list.length
      let reTitle = relatedElement ? relatedElement.title : ''
      if (rl == 1 && reTitle == '占位（请忽略）') {
        //          tool.cl('fff')
        relatedContext.list.splice(0, 1)
      }
      return true
    },
    filter_attr() {
      let has = JSON.parse(this.attr_group_str)
      let tmp = [];
      tmp = has.reduce((coll, item) => {
        let rs = coll.concat(item)
        return rs;
      }, tmp);
      //        tool.cl(tmp)
      if (this.attr)
        this.attr = this.attr.filter(item => {
          return !tmp.contains(item.id)
        });
    },
    group_init2() {
      util.getBindField(this,this.mid, 1,(zip)=> {
         if (zip) {
           this.group = zip.map(item => {
             return {
               id: item.id,
               title: item.title
             }
           })
         }
      });

    },
    group_init(fields, f) {

      fields = fields || [];
      if (fields.length == 0) {
        util.getBindField(this, this.mid, 1, (zip) => {
          if (zip) {
            this.group = zip.map(item => {
              return {
                id: item.id,
                title: item.title
              }
            })
          }
        });

        util.getBindField(this, this.mid, 2, (rs) => {
          this.attr = rs;
        });

      }


      let maped = fields.map(field => {
        return {
          id: field.id,
          title: field.title
        }
      })
      this.attr_group[0] = maped

      if (f) {
        this.pro_attr_group_str()
      } else {
        this.pro_attr_group_str()
        this.pro_group_str()
      }

      this.init2()
      this.filter_attr()

    }
  },
  watch: {
    attr: function(val, old) {
      if (val != old) {
        // tool.cl(val)
        // this.setList(val)
      }
    },
    group: function(val, old) {
      if (val) {
        this.pro_group_str()
      }
    },
    attr_group: function(val, old) {
      if (val) {

        this.pro_attr_group_str()

      }
    },
    isDragging(newValue) {
      if (newValue) {
        this.delayedDragging = true
        return
      }
      this.$nextTick(() => {
        this.delayedDragging = false
      })
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: 'description',
        disabled: !this.editable,
        ghostClass: 'ghost'
      };
    },
    show() {
      return this.group.length > 0
    },
    placeholder() {
      return `请输入${this.field.title}`
    },
  },
  props: ['field', 'mid'],
  created() {

    let fields = []
    if (this.$store.state.global.op == 'update') {
      let vo = this.$store.state.global.editVo

      let group_str_zip = vo.group_str_zip
      if (group_str_zip && group_str_zip != '[]') {
        util.getBindField(this, this.mid, 2, (fields) => {
          this.group_init2();
          this.pro_group_str()

          if (vo.attr_group_str_zip && vo.attr_group_str_zip != '[]') {
            let tmp = {}
            fields.forEach(field => {

              tmp[field.id] = {
                id: field.id,
                title: field.title
              }

            })
            this.attr = fields

            let attr_group = JSON.parse(vo.attr_group_str_zip);
            this.attr_group = attr_group.map(group => {
              return group.filter(id => id != -1).map(id => {
                if (tmp[id])
                  return {
                    id: id,
                    title: tmp[id].title
                  }
              }).filter(item => item);
            })

            this.pro_attr_group_str()

            let eventVue = util.store.get(this,'eventVue');
            eventVue.$emit('zipLoad', this.attr_group_str)

            this.init2()
            this.filter_attr()

          } else {
            this.group_init(fields, 1)
          }
        });

      } else {
        this.group_init(fields)
      }

    }


    let eventVue = util.store.get(this,'eventVue');
    eventVue.$on('yes_event_search', this.yes_event)
  },
  destroyed() {
    let eventVue = util.store.get(this,'eventVue');
    eventVue.$off('yes_event_search', this.yes_event)
  },
  mounted() {}
};
</script>

<style rel="stylesheet/less" lang="less" scoped>@import "../../common/style/mixin";
@dir: "edit/";

.flip-list-move {
    transition: transform 0.5s;
}

.ui.vertical.menu {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

}

.attrGroupSearchWrapper {
    .sortMenu();
    .ui.menu > .item:first-child {
        padding: 0.92857143em 1.14285714em;
    }
}
</style>
